﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LanguageInfo.IDAL;
using LanguageInfo.Factory;
using LanguageInfo.Entity;
using LanguageInfo.Common;
using System.Web;
using LanguageInfo.Common.Enum;
using System.Collections;
using LanguageInfo.Common.Utilities;
using System.Transactions;

namespace LanguageInfo.BLL
{
    public class UserInfoBLL
    {
        IUserInfoDAL narInfoDAL = LanguageInfoFactory.CreateUserInfoDAL();
        #region 注销
        public static void Logout()
        {
            HttpContext.Current.Session.RemoveAll();
            HttpContext.Current.Session.Clear();
            HttpContext.Current.Session.Abandon();
            MenuInfoBll.MenuTypeEntity = null;
        }
        #endregion

        public static bool IsRole(string strPageUrl, int intType)
        {
            bool reRl = false;
            List<MenuTypeEntity> MenuTypeEntity = MenuInfoBll.GetMenuType((UserInfoEnum.UserRoleType)intType);
            if (MenuTypeEntity.Count > 0)
            {
                for (int i = 0; i < MenuTypeEntity.Count; i++)
                {
                    if (MenuTypeEntity[i].MeunSecEntList.Count > 0)
                    {
                        for (int z = 0; z < MenuTypeEntity[i].MeunSecEntList.Count; z++)
                        {
                            if (MenuTypeEntity[i].MeunSecEntList[z].Url == strPageUrl)
                            {
                                return true;
                            }
                        }
                    }
                }
            }
            return reRl;
        }

        public static List<EnumsEntity> UserSexInfo()
        {
            List<EnumsEntity> SexEnumType = EnumsHepler.GetEnumsToEntityList(typeof(UserInfoEnum.UserSex));
            return SexEnumType;
        }
        public static UserInfo SessionUserInfo
        {
            get
            {
                return HttpContext.Current.Session["UserInfo"] as UserInfo;
            }
            set
            {
                HttpContext.Current.Session["UserInfo"] = value;
            }
        }

        public int InsertUserInfo(UserInfo _objEntity)
        {
            try
            {
                return narInfoDAL.InsertUserInfo(_objEntity);
            }
            catch (Exception ex)
            {
                LoginErr.log(ex);
                throw;
            }
        }

        public List<UserInfo> GetAllUserInfo()
        {
            try
            {
                return narInfoDAL.GetAllUserInfo();
            }
            catch (Exception ex)
            {
                LoginErr.log(ex);
                throw;
            }
        }
        public int UpdateUserInfoType(string _Account, int _Type)
        {
            try
            {
                if (_Type == (int)UserInfoEnum.UserType.Logout)
                {
                    _Type = (int)UserInfoEnum.UserType.Allow;
                }
                else
                {
                    _Type = (int)UserInfoEnum.UserType.Logout;
                }
                return narInfoDAL.UpdateUserInfoType(_Account, _Type);
            }
            catch (Exception ex)
            {
                LoginErr.log(ex);
                throw;
            }
        }
        public void DelUserInfoType(string[] _AccountArry)
        {
            try
            {
                using (TransactionScope trans = new TransactionScope())
                {
                    for (int i = 0; i < _AccountArry.Length; i++)
                    {
                        narInfoDAL.DelUserInfoType(_AccountArry[i]);
                    }
                    trans.Complete();
                }
            }
            catch (Exception ex)
            {
                LoginErr.log(ex);
                throw;
            }
        }
        public int UpdateUserInfoRole(string _Account, int _Role)
        {
            try
            {
                return narInfoDAL.UpdateUserInfoRole(_Account, _Role);
            }
            catch (Exception ex)
            {
                LoginErr.log(ex);
                throw;
            }
        }
        public UserInfo GetOnlyUserInfo(string _Account)
        {
            try
            {
                return narInfoDAL.GetOnlyUserInfo(_Account);
            }
            catch (Exception ex)
            {
                LoginErr.log(ex);
                throw;
            }
        }

        public string GetUserInfoPage(ArrayList objArryParamName, ArrayList objArryParam, int PageSize, int pageNo)
        {
            try
            {
                int startIndex = 0;
                int endIndex = 0;
                int start = 0;
                if (pageNo > 0)
                    start = (pageNo - 1) * PageSize;
                startIndex = start;
                endIndex = start + PageSize;
                FlexigridObject objJosn = new FlexigridObject();
                int intTotal = narInfoDAL.GetAllUserInfoPageCount(objArryParamName, objArryParam);
                List<UserInfo> objList = narInfoDAL.GetAllUserInfoPage(objArryParamName, objArryParam, startIndex, endIndex);

                objJosn.total = intTotal;
                objJosn.page = pageNo;
                List<FlexigridRow> objListRow = new List<FlexigridRow>();
                for (int i = 0; i < objList.Count; i++)
                {
                    FlexigridRow objRow = new FlexigridRow();
                    objRow.id = Convert.ToString(start + i + 1);
                    List<string> objListStr = new List<string>();
                    objListStr.Add(objRow.id);
                    objListStr.Add(objList[i].Account);
                    objListStr.Add(objList[i].UserName);
                    objListStr.Add(EnumsHepler.GetEnumsDescription(typeof(UserInfoEnum.UserSex), objList[i].Sex));
                    objListStr.Add(objList[i].Company);
                    objListStr.Add(objList[i].Address);
                    objListStr.Add(objList[i].ZipCode);
                    objListStr.Add(objList[i].Phone);
                    objListStr.Add(objList[i].Email);
                    string htmlRole = strHtmlRole(objList[i].Role, objList[i].Account);
                    objListStr.Add(htmlRole);
                    //objListStr.Add(EnumsHepler.GetEnumsDescription(typeof(UserInfoEnum.UserRoleType), objList[i].Role));
                    string strHtmlType = string.Format("<a href=\"javascript:void(0)\" onclick=\"OnChangeType('{0}','{1}')\">{2}</a>", objList[i].Account, objList[i].Type, EnumsHepler.GetEnumsDescription(typeof(UserInfoEnum.UserType), objList[i].Type));
                    objListStr.Add(strHtmlType);
                    objListStr.Add(objList[i].LoginTime.ToShortDateString());
                    objListStr.Add(objList[i].CreateTime.ToShortDateString());
                    objRow.cell = objListStr;
                    objListRow.Add(objRow);
                }
                objJosn.rows = objListRow;
                return JsonHelper.Serializer(objJosn);
            }
            catch (Exception ex)
            {
                LoginErr.log(ex);
                throw;
            }
        }
        static List<EnumsEntity> UserRoleList = EnumsHepler.GetEnumsToEntityList(typeof(UserInfoEnum.UserRoleType));
        private string strHtmlRole(int strChkRole, string strAccount)
        {
            StringBuilder strHtml = new StringBuilder();

            strHtml.Append(string.Format("<select name=\"ddLRole\" onchange=\"OnChangeRole(this,'{0}')\">", strAccount));
            for (int i = 0; i < UserRoleList.Count; i++)
            {
                if (strChkRole == (int)UserRoleList[i].Value)
                {
                    strHtml.Append("<option selected=\"selected\" value=\"" + UserRoleList[i].Value + "\">" + UserRoleList[i].Text + "</option>");
                }
                else
                {
                    strHtml.Append("<option value=\"" + UserRoleList[i].Value + "\">" + UserRoleList[i].Text + "</option>");
                }
            }
            strHtml.Append("</select>");
            //strHtml.Append("");

            return strHtml.ToString();
        }

        /// <summary>
        /// 验证是否有效登录
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static LoginResult ValidatedLogin(string username, string password)
        {
            if (username.Trim() == "")
            {
                return LoginResult.NoUser;
            }
            if (password.Trim() == "")
            {
                return LoginResult.NoPassword;
            }

            UserInfo objUser = new UserInfoBLL().GetOnlyUserInfo(username.Trim());

            if (string.IsNullOrEmpty(objUser.Account))
            {
                return LoginResult.NoUser;
            }
            else
            {
                if (objUser.Password == DateHelper.strMd5(password.Trim()))
                {
                    if (objUser.Type == (int)UserInfoEnum.UserType.Allow)
                    {
                        UserInfoBLL.SessionUserInfo = objUser;
                        return LoginResult.Success;
                    }
                    else//用户已经无任何权限？注销
                    {
                        return LoginResult.UserOrPasswordError;
                    }
                }
                else
                {
                    return LoginResult.NoPassword;
                }
            }
        }


        public enum LoginResult
        {
            NoUser = 1,
            NoPassword = 2,
            UserError = 3,
            Password = 4,
            Success = 5,
            NoDept = 6,
            IsLock = 7,
            IsOverDate = 8,
            UserOrPasswordError = 9
        }
    }

}
  